#!/usr/bin/env python
#encoding:UTF-8
from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://tdh:YbslTdh1@rds77jvjmmnaurb.mysql.rds.aliyuncs.com:3306/picbook'
db = SQLAlchemy(app)

class Book(db.Model):
    id = db.Column(db.Integer,primary_key=True)
    name = db.Column(db.String(64),unique=True)
    cover = db.Column(db.String(128))
    status = db.Column(db.Integer)
    pics = db.relationship('Pic',backref="book", lazy='dynamic')

    def __init__(self,name,cover,status):
        self.name = name
        self.cover = cover
        self.status = status

    def add(self):
        try:
            db.session.add(self)
            db.session.commit()
            return self.id
        except Exception,e:
            db.session.rollback()
            return e
        finally:
            return 0

    def find(self):
        temp = Book.query.filter_by(name=self.name).first()
        return temp

class Pic(db.Model):
    id = db.Column(db.Integer,primary_key=True)
    ossname = db.Column(db.String(128))
    bookid = db.Column(db.Integer,db.ForeignKey('book.id'))
    page = db.Column(db.Integer)
    def __init__(self,ossname,page):
        self.ossname = ossname
        self.page = page

    def add(self):
        try:
            db.session.add(self)
            db.session.commit()
            return self.id
        except Exception,e:
            db.session.rollback()
            return e
        finally:
            return 0

    def find(self):
        temp = Pic.query.filter_by(bookid = self.bookid,page = self.page).first()
        return temp


if __name__ == "__main__":
    b = Book("测试名称","sdfe",2);
    c = Pic('123',1,2)
    b.add()

    print b.find();
    print c.find()
    c.add()
    print c.find()
